package top.hepingan.cloudsystem.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.hepingan.cloudcommon.entity.User;
import top.hepingan.cloudcommon.exceptions.ExceptionMessages;
import top.hepingan.cloudcommon.exceptions.LoginPasswordException;
import top.hepingan.cloudcommon.exceptions.RegistrationException;
import top.hepingan.cloudcommon.mapper.UserMapper;
import top.hepingan.cloudcommon.utils.UserUtils;
import top.hepingan.cloudsystem.service.AuthService;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserMapper userMapper;

    private final static String SALT = "hepingan";

    @Override
    public String login(User user) {
        final User u = userMapper.selectOne(new QueryWrapper<User>()
                .lambda()
                .eq(User::getUsername, user.getUsername())
                .eq(User::getPassword, SaSecureUtil.md5BySalt(user.getPassword(), SALT))
        );
        if (u == null) {
            throw new LoginPasswordException(ExceptionMessages.EMAIL_LOGIN_PWD_ERR);
        }
        StpUtil.login(u.getUserId());
        //设置具体TOKEN Session权限
        StpUtil.getSession().set("ROLE", u.getRole());
        return StpUtil.getTokenValue();
    }

    @Override
    public void register(User user) {
        if (userMapper.selectOne(new QueryWrapper<User>()
                .lambda().eq(User::getUsername, user.getUsername())
                .select(User::getUserId)) != null) {
            throw new RegistrationException(ExceptionMessages.ACCOUNT_ALREADY_EXISTS_ERR);
        }
        userMapper.insert(new User()
                .setUsername(user.getUsername())
                .setRole("USER")
                .setPassword(SaSecureUtil.md5BySalt(user.getPassword(), SALT)));
    }

    @Override
    public User detail(Integer userId) {
        return userMapper.selectById(userId);
    }


}
